package com.presto.directo.mvvm.view

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.location.LocationManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.view.*
import androidx.fragment.app.Fragment
import com.presto.directo.R
import com.presto.directo.base.BaseFragment
import com.presto.directo.databinding.FragmentDefaultBinding
import com.presto.directo.databinding.LayoutPermissionDialogBinding
import com.presto.directo.net.*
import com.presto.directo.net.ApiService.Companion.URL_PRIVATE
import com.presto.directo.utils.*
import com.tbruyelle.rxpermissions3.RxPermissions
import kotlinx.coroutines.*
import kotlinx.coroutines.rx3.awaitFirst
import kotlin.random.Random

@Suppress("DeferredResultUnused")
class LoanFragment : BaseFragment() {

    private val binding by lazy { FragmentDefaultBinding.inflate(layoutInflater) }
    private val deviceInfoUtil by lazy { DeviceInfoUtil(requireActivity()) }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        Af.show_loan_page.track(mActivity)
        return binding.root
    }

    override fun initEvent() {
        val notices = arrayListOf<String>()
        for (i in 0..100) {
            val amount = (Random.nextInt(10) + 15) * 100
            val notice = "¡Felicidades al cliente " + (Random.nextInt(79999) + 20000) + "*****" + " por su préstamo exitoso " + amount + "$ !"
            notices.add(notice)
        }
        binding.nv.start(notices)
        binding.btnLoan.setOnClickListener {
            mActivity.loginWith {
                Af.click_loan.track(mActivity)
                start(onNext = {
                    val granted = RxPermissions(this).request(*PERMISSIONS.toTypedArray()).awaitFirst()
                    if (granted) {
                        val locationManager = mActivity.getSystemService(Context.LOCATION_SERVICE) as LocationManager
                        if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                            toast("Favor de activar el servicio de ubicación")
                            startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
                            return@start
                        }
                        showProgress()
                        val deferredList = pushId.map {
                            push(mActivity, deviceInfoUtil, it)
                        }
                        deferredList.forEach { it.await().getResultOrNull() }
                        val dataStatusEntity = getApiService().getDataStatus(getHttpMap().sign(11)).getResult()
                        val page = when {
                            dataStatusEntity.region_status != "1" -> InfoAddressActivity::class.java
                            dataStatusEntity.work_status != "1" -> InfoWorkActivity::class.java
                            dataStatusEntity.credit_status != "1" -> InfoQuestionActivity::class.java
                            dataStatusEntity.contact_status != "1" -> InfoContactActivity::class.java
                            dataStatusEntity.person_status != "1" -> InfoPersonActivity::class.java
                            else -> CardListActivity::class.java
                        }
                        startActivity(Intent(mActivity, page))
                    } else {
                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                        intent.data = Uri.parse("package:${mActivity.packageName}")
                        startActivity(intent)
                    }
                }, onComplete = {
                    dismissProgress()
                })
            }
        }
        binding.rlPrivate.setOnClickListener {
            val intent = Intent(mActivity, WebActivity::class.java)
            intent.putExtra("url", URL_PRIVATE)
            intent.putExtra("title", getString(R.string.text_private_title))
            startActivity(intent)
        }
        binding.rlPermission.setOnClickListener {
            mActivity.showDialog(1f, Gravity.BOTTOM) { dialog ->
                val binding = LayoutPermissionDialogBinding.inflate(layoutInflater)
                dialog.setContentView(binding.root)
                dialog.setCanceledOnTouchOutside(true)
                binding.tvPrivate.text = SpannableStringBuilder()
                    .append("""Al presionar "CONTINUAR" se entenderá que has revisado , leído y aceptado los términos de nuestro """.trimIndent())
                    .append(mActivity.setTextClick("Aviso de Privacidad", URL_PRIVATE) {
                        dialog.dismiss()
                        val intent = Intent(mActivity, WebActivity::class.java)
                        intent.putExtra("url", URL_PRIVATE)
                        intent.putExtra("title", "Aviso de Privacidad")
                        startActivity(intent)
                    })
                binding.tvPrivate.movementMethod = LinkMovementMethod.getInstance()
                binding.tvPrivate.highlightColor = Color.TRANSPARENT
                binding.tvConfirm.setOnClickListener {
                    dialog.dismiss()
                    start(onNext = {
                        RxPermissions(this).request(*PERMISSIONS.toTypedArray()).awaitFirst()
                        if (UserUtil.isLogin()) {
                            pushId.forEach {
                                push(mActivity, deviceInfoUtil, it)
                            }
                        }
                    }, toast = false)
                }
            }
        }
        binding.rlFaq.setOnClickListener {
            val intent = Intent(mActivity, WebActivity::class.java)
            intent.putExtra("url", ApiService.URL_QUESTION)
            intent.putExtra("title", getString(R.string.text_mine_question))
            startActivity(intent)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        locationUtil.stopLocation()
    }

    companion object {
        fun createFragment(): Fragment {
            return LoanFragment().apply {

            }
        }
    }
}